# -*- coding:utf-8 -*-

from server.util import errors, sqlBuild, stringUtil


class batchBase(object):
    def __init__(self, db, re=None):
        self.db = db
        self.re = re

    @staticmethod
    def idChecked(func):  # 对每一次请求进行id检测
        def wrapper(*args, **kw):
            db, re = args[0].db, args[0].re
            baId = args[1][0]  # 基站id
            lb = stringUtil.redis_key_name(baId)
            bel = stringUtil.redis_key_name(baId, "be")
            rekey = re.lindex(lb, 1)

            if rekey is None:
                sql = sqlBuild.sqlDict["select_baseStation_register"] % baId
                isHave = db.select(sql)  # 检测基站id是否存在
                if isHave[0]["num"] == 0:
                    raise errors.Illegal("error[1002]: 未注册的设备")
                else:
                    sql = sqlBuild.sqlDict["select_baseStation_queenAnt"] % baId
                    sectionId = db.select(sql)  # 检测基站对应路段id
                    re.lpush(lb, 0, sectionId[0]["sectionId"])
                    re.set(bel, 0)

            if re.lindex(lb, 1) != "bell":
                re.lset(lb, 1, 0)  # 将心跳更新为0

            return func(*args, **kw)

        return wrapper
